var router = require('libs/router').router;
var pages = require('libs/pages');
var ItemMixin = require('mixins/item');
var libs = require('libs/libs');
var api = libs.api;
var pageData = false;
var store = require('mixins/store')
var _sendDId;

var bindEvent = function(){

    libs.inject()
        .js(['/js/t/jq/ui.js', 'uiLib'], express);

    function express(){
    }
    //查看更多订单状态
    $('.dHO_link .link_more').click(function(){
        router('send/status',{orderid: pageData.userOrder.orderId});
    });
    //查看物流信息
    $('.send-exp-list .block').click(function(){
        var exp = $(this).find('.exp').text();  //快递公司名称
        var bill = $(this).find('.bill').text(); //快递单号
        var _orderId = pageData.userOrder.orderId;
        localStorage.setItem('savehistory',JSON.stringify(SA.get('_HISTORY')))
            // router('http://m.kuaidi100.com/index_all.html?type='+exp+'&postid='+bill+'&callbackurl=http://192.168.1.43:3000/app?hash=send/details&orderId='+_orderId.orderId)
        router('http://m.kuaidi100.com/index_all.html?type='+exp+'&postid='+bill+'&callbackurl=http://192.168.1.43:3000/app?hash=send/details&orderId='+_orderId)

        // var _orderId = JSON.parse(sessionStorage.getItem('sendOrderId'));
        // window.location.href = 'http://m.kuaidi100.com/index_all.html?type='+exp+'&postid='+bill+'&callbackurl=http://192.168.1.43:3000/app?hash=send/details&orderId='+_orderId.orderId;
    })
    //评分 / 查看评分
    $('.comments a').click(function(){
        // var num = $(this).attr('data-num');  //分数
        // var isAbleScore = $(this).attr('data-status');  //是否可以评分
        // var _orderId = JSON.parse(sessionStorage.getItem('sendOrderId'));
        // var _status = num ? 'COMPLETEEVALUATE' : 'TOEVALUATE';
        // if(isAbleScore==0){
        //     return;
        // }
        router('water/comments', {backid: pageData.userOrder.orderId, backstatus: pageData.userOrder.status});
    });
    //取消订单
    $('.cancel-order-btn').click(function(){
        // var _orderId = $(this).attr('data-id');
        // console.log(pageData);
        var _pkgSendId = pageData.pkgSend.pkgSendId;
        var login = SA.get('USER').login;
        var params = {
            method : 'get',
            login : login,
            orderId : pageData.pkgSend.orderId,
            pkgSendId : _pkgSendId
        };
        ui.alertBox({
           cons: [{text:'您是否取消寄件？',name:"bigCon"}],
           btns: [
               {
                   text: '不取消',
                   close: true
               },
               {
                   text: '取消',
                   close: false,
                   callback: function () {
                       api.req('/cancelShippment',params,function(data){
                           console.log(data);
                           $('.send-exp-list,.cancel-order-btn').hide();
                        //    $('.status-str').text('您的订单已取消，如有问题，欢迎联系我们');
                           $('.ab_cover,.m-box').remove();
                           updataOrder('cancel')
                        //    SA.setter('cancelOrder',{data: pageData})
                       });
                   }
               }
           ]
       })
    })

}

var SendDetails = React.createClass({
    mixins: [ItemMixin, store('cancelOrder')],
    // orderStatus:function(status){
    //     // APPOINTMENT 已预约
    //     // CANCEL 已取消
    //     // COMPLETE 服务完成
    //     // PAID 已支付
    //     // WAITFORPAY 待支付
    //     // TAKEN 已领单
    //     var str = '您已在线申请寄件，等待管家上门为您取件';
    //     var pkgSendLst = false;  //是否显示快递信息
    //     var cancelShow = false;  //是否显示 取消按钮
    //     switch (status) {
    //         case 'APPOINTMENT':
    //             cancelShow = true;
    //             str = '您已在线申请寄件，等待管家上门为您取件';
    //             break;
    //         case 'CANCEL':
    //             cancelShow = false;
    //             str = '您的订单已取消，如有问题，欢迎联系我们';
    //             break;
    //         case 'COMPLETE':
    //             pkgSendLst = true;
    //             cancelShow = false;
    //             str = '您的订单已完成';
    //             break;
    //     }
    //     return {
    //         str : str,
    //         pkgSendLst : pkgSendLst,
    //         cancelShow : cancelShow
    //     };
    // },
    componentWillMount: function(){
        if(this.props.data){
            this.setState({
                DData: this.props.data
            })
        }
    },
    orderStatus: function(){
        if(this.state.DData.pkgSend.status == 'APPOINTMENT'){
            return(
                <div className="cancel-order-btn" >取消订单</div>
            )
        }
    },
    willMount: function(){
        if(this.state.DData.userOrder.status == 'COMPLETEEVALUATE'){
            return(
                <div className="mT01 comments"  id="comments_off">
                    <a href="javascript:;" className="f_btn comments_btn">查看评价</a>
                </div>
            )
        }else if(this.state.DData.userOrder.status == 'TOEVALUATE'){
            return(
                <div className="mT01 comments" id="comments_on">
                    <a href="javascript:;" className="f_btn comments_btn">评价</a>
                </div>
            )
        }
    },
    render: function(){
        var CommentsStatus = this.willMount()
        var _data = this.state.DData;
        var sendDstatus = this.orderStatus(); //订单状态
        var _pkgSendLst = {}
        var sdcreateTime = _data.sendLog.createTime.substr(0,16)
        var endTimes =  _data.pkgSend.reservationPickupEndtime.substr(0,16)
        var endtimedata = endTimes.split(" ");
        var sendItem_time = _data.pkgSend.reservationPickupStarttime.substr(0,16) + '~' + endtimedata[1];
        //快递信息
        if(_data.pkgSendLines.length){
            _pkgSendLst = _data.pkgSendLines.map(function(item,index){
                return (
                    <div key={index} className="block">
                        <div className="img"><img src={item.iconUrl} /></div>
                        <div><span className="exp">{item.expressName}</span>－<span className="bill">{item.expressBill}</span></div>
                        <a className="link_more look-more-status"><i className="iconfont icon-link">查看物流</i></a>
                    </div>
                );
            });
        }

        return(
            <div className="send-details flex flex-v">
                <div className="flex-1 f-oTouch">
                    <div className="defalut_head_orders box-shadow default_pd016">
                        <em className="status-str">
                            {  (function(){
                                    var _d = _data.sendLog.description,
                                        _c = _data.sendLog.createBy;
                                    return _d.indexOf('领单')>-1 ? _c+''+_d: _d;
                                })()
                            }
                            </em>
                        <div className="dHO_link">
                            <p>{sdcreateTime}</p>
                            <a className="link_more"><i className="iconfont icon-link">查看更多</i></a>
                        </div>
                    </div>
                    {CommentsStatus}
                    <div className="order-msg box-shadow">
                        <div className="item">
                            <label>姓名</label>
                            <div className="order-msg-com">{_data.pkgSend.sendUser}</div>
                        </div>
                        <div className="item">
                            <label>电话</label>
                            <div className="order-msg-com">{_data.pkgSend.sendUserPhone}</div>
                        </div>
                        <div className="item">
                            <label>地址</label>
                            <div className="order-msg-com">{_data.pkgSend.sendAddress}</div>
                        </div>
                        <div className="item">
                            <label>预约时间</label>
                            <div className="order-msg-com">{sendItem_time}</div>
                        </div>
                        <div className="item">
                            <label>备注</label>
                            <div className="order-msg-com">{_data.pkgSend.remark}</div>
                        </div>
                    </div>

                    <div className="order-number box-shadow">
                        <div className="item">
                            <div>订单号</div>
                            <div>{_data.pkgSend.bill}</div>
                        </div>
                    </div>

                    <div className="express box-shadow send-exp-list" style={_data.pkgSendLines.length>0?{display:'block'}:{display:'none'}}>
                        {_pkgSendLst}
                    </div>

                    <div className="f_submit">
                        <a href={"tel:"+_data.provider.contactPhone} className="f_btn">客服电话</a>
                    </div>
                </div>
                {sendDstatus}
            </div>
        )
    }
})

function updataOrder(stat){
    _this = this;
    var login = SA.get('USER').login;
    var params = {
        method: 'get',
        login: login,
        orderId: _sendDId
    };
    api.req('/pkgSendDetail',params,function(data){
        console.log(data);
        if (stat==='cancel'){
            SA.setter('cancelOrder', {DData: data})
        }
        else{
            _this.main(_this,data);
        }
    });
}

function start(name){
    return pages.new({
        boot: function(){},
        // goback: function(){
        //     router.cb = function(name){
        //         pageData = false;     //页面后退，数据初始化
        //         router('send/send');   //手动返回快递寄件下单页
        //     }
        // },
        trigger: function(self, data){
            // this.libs.changeTitle('快递寄件-订单详情');
            this.libs.changeTitle('订单详情');
            var _this = this;
            if(localStorage.getItem('savehistory')){
                SA.set('_HISTORY',JSON.parse(localStorage.getItem('savehistory')))
                localStorage.removeItem('savehistory')
            }
            if(data && data.back){
                _sendDId = data.back;
                sessionStorage.setItem('expfOrderId',JSON.stringify(data.back))
            }else{
                if(sessionStorage.getItem('expfOrderId')){
                    _sendDId = JSON.parse(sessionStorage.getItem('expfOrderId'))
                    //sessionStorage.removeItem('expfOrderId')
                }
            }
            updataOrder.call(this)
            // var login = SA.get('USER').login;
            // var params = {
            //     method: 'get',
            //     login: login,
            //     orderId: _sendDId
            //     // orderId: '7f010f75aee44917a472a3c36d05350b'
            // };
            // // function statusTog(data){
            // //     var status = data.status;  //是否显示 取消按钮
            // //     switch (status) {
            // //         case 'APPOINTMENT':
            // //             $('.cancel-order-btn').show();
            // //             // $('.status-str').text('您已在线申请寄件，等待管家上门为您取件');
            // //             break;
            // //         case 'CANCEL':
            // //             $('.cancel-order-btn').hide();
            // //             // $('.status-str').text('您的订单已取消，如有问题，欢迎联系我们');
            // //             break;
            // //         case 'COMPLETE':
            // //             $('.cancel-order-btn').hide();
            // //             // $('.status-str').text('您的订单已完成');
            // //             break;
            // //     }
            // // }
            //
            // api.req('/pkgSendDetail',params,function(data){
            //     if(!data.code){
            //         pageData = data;
            //         _this.main(_this,data);
            //         //是否显示取消按钮
            //         // statusTog(pageData);
            //     }
            // });

        },
        main: function(slef,data){
            if(data){
                pageData = data
            }
            this.render(
                <SendDetails itemDefaultMethod={bindEvent} data={data} />,
                document.getElementById(name)
            )
        },
        end: function(){
            React.unmountComponentAtNode(document.getElementById(name))
        }
    })
}


module.exports = start;
